
import { Component } from '@angular/core';
import { NavController, AlertController, LoadingController, Loading } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { Register } from '../register/register';
import { HomePage } from '../home/home';
 
@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class Login {
  loading: Loading;
  registerCredentials = {username: '', password: ''};
 
  constructor(private nav: NavController, private auth: AuthService, private alertCtrl: AlertController, private loadingCtrl: LoadingController) {
  }

  public createAccount() {
    this.nav.push(Register);
  }
 
  public login() {
    this.showLoading()
    this.auth.login(this.registerCredentials).then(result => {
      if (result.access) {
        this.nav.setRoot(HomePage)
        localStorage.user = JSON.stringify(result.user)
        localStorage.factory = JSON.stringify(result.factory)
        return this.loading.dismiss();
      } else {
        this.showError("用户名或密码错误，请重新输入");
        return this.loading.dismiss();
      }
    }, error => {
      this.showError(error);
    }).catch(error => console.log(error));
  }
 
  showLoading() {
    this.loading = this.loadingCtrl.create({
      content: '登录中，请等待。。。'
    });
    this.loading.present().catch(data => {});
  }
 
  showError(text) {
    let alert = this.alertCtrl.create({
      title: '',
      subTitle: text,
      buttons: ['OK']
    });
    alert.present(prompt).catch(data => {});
  }
}
